package arg

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/gurkankaymak/hocon"
	"db2s/global"
	"os"
	"reflect"
	"runtime"
	"strings"
)

type repairLevel struct {
	Fix      string `json:"fix"`
	TrxNum   int    `json:"trxNum"`
	Binlog   bool   `json:"binlog"`
	FileName string `json:"fileName"`
	Way      string `json:"way"`
}

var C = func(str, path string) string {
	sysType := runtime.GOOS
	switch sysType {
	case "linux":
		if n := strings.Index(path, "/"); n != -1 {
			path = path[n:]
		}
		if str != "" {
			path = fmt.Sprintf("%s/%s", str, path)
		}
	case "windows":
		if n := strings.Index(path, "\\"); n != -1 {
			path = path[n:]
		}
		if str != "" {
			path = fmt.Sprintf("%s\\%s", str, path)
		}
	}
	return path
}

func PathExists(str, path string) (string, bool, error) {
	var err error
	if str == "" {
		str, _ = os.Getwd()
	}
	path = C(str, path)
	if _, err = os.Stat(path); err != nil {
		if err = os.MkdirAll(path, os.ModePerm); err != nil {
			err = errors.New(fmt.Sprintf("mkdir dir %s failed! error message is %v", path, err))
			return "", false, err
		}
	}
	return path, true, nil
}

// repair parameter check
func repairSecondaryLevelParameter(repair hocon.Object) (repairV RepairS, err error) {
	var (
		repairMap map[string]any
		//err       error
		s2 []string
	)
	if repairMap, err = global.StructToMapAny(getRepair()); err != nil {
		return
	}
	for k, v := range repairMap {
		if r1 := rc.getHoconConfigVal(repair.ToConfig(), k, reflect.TypeOf(v).String()); r1 != nil {
			s3 := rc.anyToJsonString(k, r1)
			if strings.Contains(s3, "false") && strings.EqualFold(k, "fix") {
				s3 = strings.ReplaceAll(s3, "false", "no")
			}
			s2 = append(s2, s3)
		} else {
			s2 = append(s2, rc.anyToJsonString(k, v))
		}
	}
	if err = json.Unmarshal([]byte(fmt.Sprintf("{%s}", strings.Join(s2, ","))), &repairV); err != nil {
		return
	}
	return
}

type repairModeCheck struct {
	FunctionalMode    []string       `json:"funcMode"`
	FuncPassParameter map[string]any `json:"funcPass"`
}

// repairDataFixFileSplitActive
func repairDataFixFileSplitActive(p *SecondaryLevel) (err error) {
	if p.RepairV.FixFilePathBase, err = global.JoinPath("", "dataFix"); err != nil {
		return err
	}
	if _, err = global.EnsurePathExists(p.RepairV.FixFilePathBase); err != nil {
		return err
	}
	if n := strings.LastIndex(p.RepairV.FixFileName, "/"); n != -1 {
		p.RepairV.FixFileName = p.RepairV.FixFileName[n+1:]
	}
	return
}

// repairParameterCheck
func repairParameterCheck(p *SecondaryLevel, s repairModeCheck) (err error) {
	var (
		schemaMap map[string]any
		v         map[string]any
	)
	if schemaMap, err = global.StructToMapAny(s); err != nil {
		return
	} else {
		if v, ok := schemaMap["funcMode"]; ok {
			var funcExist bool
			for _, v1 := range v.([]string) {
				if strings.EqualFold(p.FunctionalMode, v1) {
					funcExist = true
				}
			}
			if !funcExist {
				return nil
			}
		}
	}

	if v, err = global.StructSubJsonNameToMap(repairFixSqlRulesOptionValue{}); err != nil {
		return err
	} else {
		if !parameterOptions(v, p.RepairV.DataFix) {
			p.RepairV.DataFix = "file"
		}
	}
	if v, err = global.StructSubJsonNameToMap(repairFixSqlFileOptionValue{}); err != nil {
		return
	} else {
		if !parameterOptions(v, p.RepairV.FixFileWay) {
			p.RepairV.FixFileWay = "split"
		}
	}
	if p.RepairV.FixTrxNum < 1 {
		p.RepairV.FixTrxNum = 100
	}
	if p.RepairV.DataFix == "file" {
		if err = repairDataFixFileSplitActive(p); err != nil {
			return
		}
	}
	return
}
